<?php


namespace App\Services;

use App\Models\Classify;
use App\Models\PrintTemplate;
use App\Utils\Code;
use Illuminate\Database\Eloquent\Builder;

class PrintTplService extends BaseService
{

    /**
     * 创建模板
     * @param array $params
     * @return Classify|Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params, false)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = new PrintTemplate();
        $model->title = $params['title'];
        $model->mode = $params['mode'];
        $model->user_id = \Auth::id();
        if (isset($params['width']) && $params['width']) {
            $model->width = $params['width'];
        }
        if (isset($params['height']) && $params['height']) {
            $model->height = $params['height'];
        }
        if (isset($params['cover']) && $params['cover']) {
            $model->cover = $params['cover'];
        }
        if (isset($params['header']) && $params['header']) {
            $model->header = $params['header'];
        }
        if (isset($params['footer']) && $params['footer']) {
            $model->footer = $params['footer'];
        }
        if (isset($params['thead']) && $params['thead']) {
            $model->thead = $params['thead'];
        }
        if (isset($params['tfoot']) && $params['tfoot']) {
            $model->tfoot = $params['tfoot'];
        }
        if (isset($params['lists']) && $params['lists']) {
            $model->lists = $params['lists'];
        }
        if (isset($params['tpl_desc']) && $params['tpl_desc']) {
            $model->tpl_desc = $params['tpl_desc'];
        }
        $model->save();
        return $this->info($model->tpl_id);
    }

    /**
     * 模板信息
     * @param $id
     * @param bool $abnormal
     * @return PrintTemplate|Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function info($id, $abnormal = true) {
        $model = PrintTemplate::where('tpl_id', (int)$id);
        if (!($model = $model->first()) && $abnormal){
            throw new \Exception("模板信息不存在", Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新模板
     * @param array $params
     * @param $id
     * @return Classify|Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update(array $params, $id) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = $this->info($id);
        if (isset($params['title']) && $params['title']) {
            $model->title = $params['title'];
        }
        if (isset($params['mode']) && $params['mode']) {
            $model->mode = $params['mode'];
        }
        if (key_exists('width', $params)) {
            $model->width = $params['width'] ? $params['width'] : null;
        }
        if (key_exists('height', $params)) {
            $model->height = $params['height'] ? $params['height'] : null;
        }
        if (isset($params['cover']) && $params['cover']) {
            $model->cover = $params['cover'];
        }
        if (key_exists('header', $params)) {
            $model->header = $params['header'];
        }
        if (key_exists('footer', $params)) {
            $model->footer = $params['footer'];
        }
        if (key_exists('thead', $params)) {
            $model->thead = $params['thead'];
        }
        if (key_exists('tfoot', $params)) {
            $model->tfoot = $params['tfoot'];
        }
        if (key_exists('lists', $params)) {
            $model->lists = $params['lists'];
        }
        if (key_exists('tpl_desc', $params)) {
            $model->tpl_desc = $params['tpl_desc'];
        }
        $model->save();
        return $this->info($model->tpl_id);
    }

    /**
     * 删除模板
     * @param $id
     * @return bool|mixed|null
     * @throws \Exception
     */
    public function destroy($id) {
        return $this->info($id)->delete();
    }

    /**
     * 模板分页
     * @param array $params
     * @param bool $isList
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function paginate(array $params = [], $isList = true) {
        $model = PrintTemplate::select([
            'tpl_id', 'title', 'width', 'height', 'mode', 'cover', 'created_at', 'tpl_desc'
        ]);
        if (isset($params['mode']) && $params['mode']) {
            $model = $model->where('mode', $params['mode']);
        }
        if ($isList || !$this::$admin) {
            return $model->orderBy('created_at', 'desc')->get();
        } else {
            if (isset($params['title']) && $params['title']) {
                $model = $model->where('title', 'like', "%{$params['title']}%");
            }
            if (isset($params['width']) && is_numeric($params['width'])) {
                $model = $model->where('width', (int)$params['width']);
            }
            if (isset($params['height']) && is_numeric($params['height'])) {
                $model = $model->where('height', (int)$params['height']);
            }
            return $model->orderBy('created_at', 'desc')
                ->paginate(isset($params['per_page']) && $params['per_page'] ? (int)$params['per_page'] : null);
        }
    }

    /**
     * 验证参数
     * @param array $params
     * @param false $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false) {
        $rules = [
            "title" => ['bail', 'required', 'string', 'between:2,30'],
            "mode" => ['bail', 'required', 'string'],
            "lists" => ['bail', 'nullable', 'array'],
            "lists.item_list" => ['bail', 'nullable', 'array'],
            "lists.item_list.*.title" => ['bail', 'required', 'string'],
            "lists.item_list.*.field" => ['bail', 'required', 'string'],
            "lists.item_list.*.width" => ['bail', 'nullable', 'integer', 'gt:0'],
            "lists.fixed_title" => ['bail', 'nullable', 'integer', 'in:0,1']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    $rule[1] = 'nullable';
                }
            }
        }
        $validator = \Validator::make($params, $rules, [], [
            "title" => "模板标题",
            "mode" => "模板分类",
            "lists" => '数据列表数据集',
            "lists.item_list" => '列表字段数据集',
            "lists.item_list.*.title" => '列表字段标题',
            "lists.item_list.*.field" => '列表字段标识',
            "lists.item_list.*.width" => '列表字段宽度',
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
